package com.mes.controller;

import com.mes.utils.DBConctionQuery;
import com.yy.base.servlet.upload.File;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.Map;

public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 7618658514199005769L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			String id = request.getParameter("id");
			String[] file = this.getFile(id);

			String fileName = file[0];
			String filePath = file[1];
			if (fileName == null) {
				fileName = "filename";
			}
			downLoad(filePath, response, fileName);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private String[] getFile(String id) {
		DBConctionQuery query = null;
		try {
			query = new DBConctionQuery();

			String sql = "select name, path from emes_file where emes_file_id = ?";
			Map<String, Object> map = query.queryUnique(sql, id);
			if (map != null) {
				return new String[]{(String) map.get("name"), (String) map.get("path")};
			}
		} catch (Exception e) {
		} finally {
			if (query != null)
				query.close();
		}
		return null;
	}

    /**
	 * 下载
	 * @param filePath 文件路径
	 */
	public void downLoad(String filePath, HttpServletResponse response, String fileName) throws Exception {
		File f = new File(filePath);
		if (!f.exists()) {
			response.sendError(404, "File not found!");
			return;
		}
		BufferedInputStream br = null;
		OutputStream out = null;
		try {
			br = new BufferedInputStream(new FileInputStream(f));
			String name = new String(fileName.getBytes("GBK"), "iso8859-1"); // 修改编码
			byte[] buf = new byte[1024];
			int len = 0;
			response.reset(); // 非常重要

			URL u = new URL("file:///" + filePath);
			response.setContentType(u.openConnection().getContentType());
			response.setHeader("Content-Disposition", "inline; filename=" + name);
			out = response.getOutputStream();
			while ((len = br.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		} catch (Exception e) {
			System.out.println("下载文件失败!" + "--" + filePath);
		} finally {
			try {
				if (br != null) {
					br.close();
				}
			} catch (Exception ex) {
			}
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
			}
		}
	}
}